#include <iostream>
#include <fstream>
#include "pb_cfg_townlist.pb.h"
#include "CSceneMgr.h"
#include "../mainctrl.h"

int CSceneMgr::LoadConfig(const char* szCfgPath)
{
    int iRet = 0;

    if (NULL == szCfgPath)
    {
        CT_ERROR(("Scene Cfg Path is null"));
        return RET_SYSTEM_FAIL;
    }

    pb_cfg_townlist stTownListCfg;
    std::fstream stFileInput(szCfgPath, std::ios::in | std::ios::binary);
    if (!stTownListCfg.ParseFromIstream(&stFileInput))
    {
        CT_ERROR(("Failed to Parse SceneCfg!"));
        return RET_SYSTEM_FAIL;
    }

    CSceneCfgData stCfgData;
    for (int i = 0; i < stTownListCfg.boss_map_list_rows_size(); ++i)
    {
        const pb_cfg_townlist_pb_cfg_boss_map_list_unit& stSceneUnit 
            = stTownListCfg.boss_map_list_rows(i);
        if (stSceneUnit.scene_id() <= 0)
        {
            continue;
        }

        stCfgData.Clear();

        stCfgData.SetResID((short)stSceneUnit.scene_id());
        stCfgData.SetMapID((unsigned int)stSceneUnit.map_id());
        stCfgData.SetEnterX(stSceneUnit.enter_x());
        stCfgData.SetEnterY(stSceneUnit.enter_y());
        stCfgData.SetDeadBorderX(stSceneUnit.dead_border_x());
        stCfgData.SetDeadBorderY(stSceneUnit.dead_border_y());
        stCfgData.SetMonGroupID((unsigned int)stSceneUnit.monster_group_id());
        stCfgData.SetLeftGroupID((unsigned int)stSceneUnit.left_group_id());
        stCfgData.SetRightGroupID((unsigned int)stSceneUnit.right_group_id());
        stCfgData.SetMonsterInitX(stSceneUnit.monster_init_x());
        stCfgData.SetMonsterInitY(stSceneUnit.monster_init_y());
        stCfgData.SetRelayMapID((unsigned int)stSceneUnit.relay_map());
        stCfgData.SetAuxRelayMapID((unsigned int)stSceneUnit.relay_map_1());

        iRet = IsValidMonGroupID(stCfgData.GetResID(),
            stCfgData.GetMonGroupID());
        CT_RETURN(iRet);

        iRet = IsValidMonGroupID(stCfgData.GetResID(),
            stCfgData.GetLeftGroupID());
        CT_RETURN(iRet);

        iRet = IsValidMonGroupID(stCfgData.GetResID(),
            stCfgData.GetRightGroupID());
        CT_RETURN(iRet);

        iRet = _stSceneCfg.AddConfig(stCfgData);
        CT_RETURN(iRet);
    }

    return 0;
}

int CSceneMgr::IsValidMonGroupID(int iSceneID, unsigned int uiMonGroupID)
{
    int iIndex = 0;

    if (uiMonGroupID > 0)
    {
        iIndex =
         CMainCtrl::m_pstMain->m_stMonsterConfigMgr.FindMonsterGroupConfig(
                 uiMonGroupID);
        if (iIndex < 0)
        {
            CT_ERROR(("monster group(%u) empty in scene cfg(%d)",
                      uiMonGroupID,iSceneID));
            return ERROR_MONSTER_NO_MONSTER_GROUP_CONFIG;
        }
    }

    return 0;
}
